package val.to.uploader.old;

import java.io.IOException;

import org.json.JSONObject;

import val.to.BitmapUtil;
import val.to.Globals;
import val.to.ValtoServices;
import val.to.entities.PhotoPost;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;

public class FacebookUploader extends AsyncTask<Void, Void, Void> implements IPhotoUploader{

	private Uri mImageUri;
	private Context mCtx;
	private String mComment;
	private boolean mResult = true;
	private IPhotoUploadListener mListener;
	
	public FacebookUploader(Context ctx, Uri imageUri, String comment, IPhotoUploadListener listener){
		mImageUri = imageUri;
		mCtx = ctx;
		mComment = comment;
		mListener = listener;
	}
	
	
	@Override
	protected Void doInBackground(Void... params) {
		//1. Rescale the image
		Bundle reqParam = new Bundle();
		try{
			reqParam.putByteArray("photo", BitmapUtil.scaleImage(mCtx.getContentResolver(), mImageUri));
			//reqParam("caption", "FbAPIs Sample App photo upload");
		}
		catch (IOException e) {
			mResult = false;
		    e.printStackTrace();
		}
		
		if (!mResult || isCancelled()){
			return null;
		}
		
		//2. Upload image to FB
		String resp = "";
		try {
			resp = Globals.FacebookSession.request("me/photos", reqParam, "POST");
		} catch (Exception e) {
			//Dont care about the erro rtype
			mResult = false;
			e.printStackTrace();
		}	
		
		if (!mResult || isCancelled()){
			return null;
		}
		
      	String[] tmp = resp.split("\"");
 
        //4. Request photo info
        reqParam = new Bundle();
        reqParam.putString("fields", "source,picture"); 
        try{
        	resp = Globals.FacebookSession.request(tmp[3] /* photo id */, reqParam, "GET");
		} catch (Exception e) {
			//Dont care about the erro rtype
			mResult = false;
			e.printStackTrace();
		}	
		
		if (!mResult || isCancelled()){
			return null;
		}
		
		//5. POST photo to Valto server
		JSONObject json;
		try {
			json = new JSONObject(resp);
	        String picURL = json.getString("source");
	        String tnUrl = json.getString("picture");

	        mResult = ValtoServices.postPhoto(new PhotoPost(picURL, "" /* TEMP */, tnUrl, mComment, true));
		} catch (Exception e) {
			//Dont care about the erro rtype
			mResult = false;
			e.printStackTrace();
		}	

 		return null;
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		mListener.onBeforeUpload();
	}

	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		if (mResult){
			mListener.onPhotoUploaded();
		}
		else{
			mListener.onUploadFailed();
		}
	}

	@Override
	public void cancel() {
		this.cancel(true);
	}
}
